#include "../Elogs/bitlog.h"
#include <unistd.h>
/*扩展以时间作为文件的滚动类型落地
    1.  以时间进行文件滚动，实际上以时间段进行滚动
    实现思想: 以当前系统时间取模时间段大小,可以得到是第几个时间段
*/
enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY
};

class RollByTimeSink : public log::LogSink
{
public:
    // 该构造函数同时完成打开文件,将文件操作句柄管理起来(通过ostream流管理)
    RollByTimeSink(const std::string &basename, TimeGap gap_type) : _basename(basename)
    {
        switch (gap_type)
        {
        case TimeGap::GAP_SECOND:
            _gap_size = 1;
            break;
        case TimeGap::GAP_MINUTE:
            _gap_size = 60;
            break;
        case TimeGap::GAP_HOUR:
            _gap_size = 3600;
            break;
        case TimeGap::GAP_DAY:
            _gap_size = 3600 * 24;
            break;
        }
        _cur_gap = _gap_size == 1 ? log::util::Date::getTime() : log::util::Date::getTime() % _gap_size; // 功能: 获取当前时间与上个文件的时间段是否一致

        std::string filename = createNewFile();
        log::util::File::createDirectory(log::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    // 将日志消息写入标准输出
    void log(const char *data, size_t len)
    {
        time_t cur = log::util::Date::getTime();
        if ((cur % _gap_size) != _cur_gap)
        {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data, len); // 这布就是将日志消息写入指定文件
        assert(_ofs.good());
    }

private:
    // 进行大小判断，超过指定大小则创建新文件
    std::string createNewFile()
    {
        // 获取系统时间,以时间+之前的根目录一起来构造文件扩展名
        time_t t = log::util::Date::getTime();
        struct tm lt;
        localtime_r(&t, &lt); // 将时间戳转换成年月日时分秒格式
        std::stringstream filename;
        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << "-";
        filename << ".log";
        return filename.str();
    }

private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;  // 当前是第几个时间段,
    size_t _gap_size; // 时间段大小
};

int main()
{
    std::unique_ptr<log::LoggerBuilder> builder(new log::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");
    builder->buildLoggerLevel(log::LogLevel::value::WARN);
    builder->buildLoggerFormatter("[%c][%f:%l]%m%n");
    builder->buildLoggerType(log::LoggerType::LOGGER_ASYNC);
    builder->buildSink<RollByTimeSink>("./logfile/roll-async-by-size", TimeGap::GAP_SECOND);
    log::Logger::ptr logger = builder->build();
    size_t cur = log::util::Date::getTime();
    while (log::util::Date::getTime() < cur + 5)
    {
        logger->fatal("这是一条测试日志");
        usleep(1000);
    }

    return 0;
}